<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="dialogStyle"
      title="新建跟进"
      width="700"
      @close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="formParams"
        :rules="rulesForm"
        label-width="110px"
      >
        <el-row :span="24">
          <el-col :span="11">
            <el-select
              v-model="formParams.type"
              class="w-full"
              clearable
              placeholder="请选择跟进方式"
            >
              <el-option
                v-for="(dict, index) in followup_method"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-date-picker
              v-model="formParams.followTime"
              clearable
              placeholder="请选择跟进时间"
              style="width: 100%"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-col>
          <el-col :span="24" class="mt-20px mb-20px">
            <el-input
              v-model="formParams.content"
              maxlength="300"
              placeholder="请输入跟进内容"
              rows="5"
              type="textarea"
            />
          </el-col>
        </el-row>
        <el-form-item label="上传附件：">
          <el-upload
            v-model:file-list="formParams.fileList"
            :before-upload="beforeAvatarUpload"
            :http-request="handleFileChange"
            :show-file-list="false"
            accept=".rar, .zip, .doc, .docx, .pdf"
            action="#"
            class="upload-demo"
          >
            <el-button style="font-size: 14px" type="default"
              ><el-icon><UploadFilled /></el-icon>上传</el-button
            >
            <template #tip>
              <div class="el-upload__tip float-right">
                支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
              </div>
            </template>
          </el-upload>
          <div class="text-14px mt-10px" style="width: 100%">
            <div v-for="(item, index) in fileList" :key="item.fileId">
              <a :href="item.url" class="text-#409eff" target="_blank">{{
                item.origFileName
              }}</a>
              <el-button plain text @click="delFileName(index)">删除</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          v-if="
            dialogParam.tableName != 'biz_contact' &&
            dialogParam.tableName != 'biz_telephone_record'
          "
          label="客户名称："
          prop="customer"
        >
          <el-input v-model="formParams.customer" disabled type="input" />
        </el-form-item>
        <!-- 直销客户（电话记录） start -->
        <div v-if="dialogParam.tableName == 'biz_telephone_record'">
          <el-form-item label="结果：" prop="followResult">
            <el-select
              v-model="formParams.followResult"
              class="w-full"
              clearable
              placeholder="请选择结果"
            >
              <el-option
                v-for="(dict, index) in sys_follow_result"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 直销客户（电话记录） end -->
        <!-- 订单模块 start -->
        <div
          v-if="
            dialogParam.tableName == 'ord_order' ||
            dialogParam.tableName == 'ord_purchase_order' ||
            dialogParam.tableName == 'ord_inner_order'
          "
        >
          <el-form-item label="订单标题：" prop="orderName">
            <el-input v-model="formParams.orderName" disabled type="input" />
          </el-form-item>
        </div>
        <!-- 订单模块 end -->
        <!-- 客户模块 商机模块 start -->
        <div
          v-else-if="
            dialogParam.tableName == 'biz_customer' ||
            dialogParam.tableName == 'ord_business_opportunity' ||
            dialogParam.tableName == 'ord_small_medium'
          "
        >
          <el-form-item
            :label="
              dialogParam.tableName == 'biz_customer'
                ? '客户状态：'
                : '商机阶段：'
            "
            prop="status"
          >
            <el-select
              v-if="dialogParam.tableName == 'biz_customer'"
              v-model="formParams.status"
              clearable
              placeholder="请选择客户状态"
              style="width: 100%"
            >
              <el-option
                v-for="(dict, index) in customer_status"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
            <el-select
              v-else
              v-model="formParams.status"
              clearable
              placeholder="请选择商机阶段"
              style="width: 100%"
              @change="businessStage"
            >
              <el-option
                v-for="(dict, index) in business_stage"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="
              dialogParam.tableName != 'ord_business_opportunity' &&
              dialogParam.tableName != 'ord_small_medium'
            "
            label="联系人："
            prop="linkId"
          >
            <el-select
              v-model="formParams.linkId"
              :remote-method="queryContacts"
              class="w-full"
              clearable
              filterable
              placeholder="请选择联系人"
              remote
              @change="contactsChange"
            >
              <el-option
                v-for="item in contactsOptions"
                :key="item.id"
                :label="item.contactName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.contactName }}</span>
                  <span>{{
                    item.contactNumber ? '(' + item.contactNumber + ')' : ''
                  }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 商机 start-->
          <el-row
            v-if="
              dialogParam.tableName == 'ord_business_opportunity' ||
              dialogParam.tableName == 'ord_small_medium'
            "
            :span="24"
          >
            <el-col :span="12">
              <el-form-item label="联系人：" prop="attnName">
                <el-input
                  v-model="formParams.attnName"
                  placeholder="请输入联系人"
                  type="input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话：" prop="attnPhone">
                <el-input
                  v-model="formParams.attnPhone"
                  placeholder="请输入联系电话"
                  type="input"
                />
              </el-form-item>
            </el-col>
            <el-col v-if="isOutflowName" :span="12">
              <el-form-item
                label="流失商机原因："
                label-width="110"
                prop="outflowName"
              >
                <el-select
                  v-model="formParams.outflowCode"
                  class="w-full"
                  clearable
                  placeholder="请选择流失商机"
                  @change="outflowCodeFn"
                >
                  <el-option
                    v-for="(item, index) in lost_business_opportunities"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="isOutflowName ? 12 : 24">
              <el-form-item label="职位：" prop="job">
                <el-input
                  v-model="formParams.job"
                  placeholder="请输入职位"
                  type="input"
                />
              </el-form-item>
            </el-col>

            <!-- 商机 end-->
          </el-row>
        </div>
        <!-- 客户模块 商机模块 end -->
        <!-- 联系人 start-->
        <div v-else-if="dialogParam.tableName == 'biz_contact'">
          <el-form-item label="联系人：" prop="linkName">
            <el-input v-model="formParams.linkName" disabled type="input" />
          </el-form-item>
        </div>
        <!-- 联系人 end-->
        <!-- 项目模块 start -->
        <div v-else-if="dialogParam.tableName == 'ord_project'">
          <el-form-item label="项目名称：" prop="proName">
            <el-input v-model="formParams.proName" disabled type="input" />
          </el-form-item>
        </div>
        <!-- 项目模块 end -->
        <el-form-item label="提醒谁看：" prop="principalId">
          <el-select
            v-model="formParams.principalId"
            class="w-full"
            clearable
            multiple
            placeholder="请选择提醒谁看"
            @focus="userInputFocus"
          >
            <el-option
              v-for="(item, index) in selectOptionObj['principalId']"
              :key="index"
              :label="item.label"
              :value="item.uuid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-col :span="24">
          <el-form-item label="提醒时间：" prop="remindTime">
            <el-date-picker
              v-model="formParams.remindTime"
              clearable
              placeholder="请选择跟进时间"
              style="width: 100%"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
          /></el-form-item>
        </el-col>
        <div class="footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button :loading="btnLoading" type="primary" @click="onSubmit"
            >保存</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <!-- 弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParamUse"
      @close="closeFn"
      @ok="selectDialogData"
    ></SelectDialog>
  </div>
</template>
<script name="Appendix" setup>
import { reactive, getCurrentInstance, watchEffect } from 'vue'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import { getDetailTactlistByCactName } from '@/api/customerManage/customerList'
import * as Api from '@/api/common/common.js'
import { addManage, getLatestMsg } from '@/api/system/notice'
import { pushNotifications } from '@/hooks/notification/push'
import { format } from 'date-fns'
import { validatePhoneTwo } from '@/utils/validate'
const commonStore = useCommonStore()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const props = defineProps({
  // userStore
  dialogParam: {
    required: true
  }
})
const validatePhoneFn = (rule, value, callback) => {
  const reg =
    /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/
  if (value == '' || value == undefined || value == null) {
    callback()
  } else {
    if (!reg.test(value)) {
      callback(new Error('请输入正确的电话号码或者固话号码'))
    } else {
      callback()
    }
  }
}
const data = reactive({
  businessType: 'order', //业务类型
  dialogVisible: false,
  formParams: {},
  rulesForm: {
    customer: [
      {
        required: true,
        message: '客户名称不能为空',
        trigger: ['change', 'blur']
      }
    ],
    status: [
      {
        required: true,
        message: '客户状态不能为空',
        trigger: ['change', 'blur']
      }
    ],
    linkId: [
      {
        required: true,
        message: '客户联系人不能为空',
        trigger: ['change', 'blur']
      }
    ],
    proName: [
      {
        required: true,
        message: '项目名称不能为空',
        trigger: ['change', 'blur']
      }
    ],
    orderName: [
      {
        required: true,
        message: '订单名称不能为空',
        trigger: ['change', 'blur']
      }
    ],
    followResult: [
      {
        required: true,
        message: '结果不能为空',
        trigger: ['change', 'blur']
      }
    ],
    attnName: [
      {
        required: true,
        message: '联系人不能为空',
        trigger: ['change', 'blur']
      }
    ],
    attnPhone: [
      {
        required: false,
        validator: validatePhoneFn,
        trigger: ['blur', 'change']
      }
    ]
  },
  dialogParamUse: {}, //选择人员弹出框
  selectOptionObj: {}, // 提醒谁看
  msgData: null //消息推送参数
})
const {
  businessType,
  dialogVisible,
  formParams,
  rulesForm,
  dialogParamUse,
  selectOptionObj,
  msgData
} = toRefs(data)
const {
  lost_business_opportunities,
  followup_method,
  customer_status,
  business_stage,
  sys_follow_result
} = proxy.useDict(
  'lost_business_opportunities',
  'followup_method',
  'customer_status',
  'business_stage',
  'sys_follow_result'
)
const btnLoading = ref(false)
const serviceType = ref('0') // 业务类型
watch(
  () => props.dialogParam,
  val => {
    if (JSON.stringify(props.dialogParam) != '{}') {
      console.log(props.dialogParam, 'props.dialogParam')
      init()
    }
  },
  {
    deep: true,
    immediate: true
  }
)
async function init() {
  dialogVisible.value = props.dialogParam.isVisible
  formParams.value = {
    ...JSON.parse(JSON.stringify(props.dialogParam)),
    remindTime: proxy.parseTime(
      new Date(
        props.dialogParam.remindData
          ? new Date().getTime() +
            props.dialogParam.remindData * 24 * 60 * 60 * 1000
          : new Date().getTime()
      )
    )
  }
  //2024/6/24 商机不需要联系人 gbq props.dialogParam.tableName == 'ord_business_opportunity'
  if (props.dialogParam.tableName == 'biz_customer') {
    //获取联系人
    contactsOptions.value = [
      { contactName: props.dialogParam.linkName, id: props.dialogParam.linkId }
    ]
  }
  //中小客商机
  if (props.dialogParam.tableName == 'ord_small_medium') {
    formParams.value.principalId = [`U${props.dialogParam.principalId}`]
    selectOptionObj.value['principalId'] = [
      {
        label: props.dialogParam.principalName,
        uuid: `U${props.dialogParam.principalId}`,
        id: props.dialogParam.principalId
      }
    ]
  }
}
/** 推送消息url 整理 */
const followUrl = type => {
  let pushUrl,
    pushBusinessId,
    id = props.dialogParam.businessId
  switch (type) {
    case 'ord_order':
      pushBusinessId = '销售订单-跟进-' + id
      serviceType.value = '14'
      pushUrl = `/sales/indent/salesOrderDetails?salesOrderId=${id}&tabPane=FollowUpList`
      break
    case 'ord_purchase_order':
      pushBusinessId = '采购订单-跟进-' + id
      serviceType.value = '13'
      pushUrl = `/source/sourceModules/purchaseOrderDetails?purchaseOrderId=${id}&tabPane=FollowUpList`
      break
    case 'ord_inner_order':
      pushBusinessId = '内部订单-跟进-' + id
      serviceType.value = '17'
      pushUrl = `/source/sourceModules/innerOrderDetails?innerOrderId=${id}&tabPane=FollowUpList`
      break
    case 'biz_customer':
      // 客户模块
      pushUrl = `/customerManage/customerModules/customerDetails?customerId=${id}&tabPane=follow`
      pushBusinessId = '客户-跟进-' + id
      serviceType.value = '2'
      break
    case 'ord_project':
      // 项目模块
      pushUrl = `/sales/projectManage/projectDetails?id=${id}&tabPane=4`
      serviceType.value = '0'
      pushBusinessId = '项目-跟进-' + id
      break
    case 'biz_contact':
      // 联系人模块
      pushUrl = `/customerManage/contactsModules/contactsDetails?contactsId=${id}&tabPane=follow`
      serviceType.value = '12'
      pushBusinessId = '联系人-跟进-' + id
      break
    case 'ord_business_opportunity':
      //商机模块
      pushUrl = `/sales/businessManage/businessDetails?id=${id}&tabPane=3`
      serviceType.value = '16'
      pushBusinessId = '商机-跟进-' + id
      break
    case 'ord_small_medium':
      //中小客商机模块
      pushUrl = `/callCenter/smallClients/businessDetails?id=${id}&tabPane=3`
      serviceType.value = '16'
      pushBusinessId = '商机-跟进-' + id
      break
  }
  return { url: pushUrl, businessId: pushBusinessId }
}
// 保存
const onSubmit = () => {
  proxy.$refs['ruleFormRef'].validate(async (valid, done, msg) => {
    if (valid) {
      if (!formParams.value.type) {
        proxy.$modal.msgError('跟进方式不能为空')
        return false
      }
      if (!formParams.value.followTime) {
        proxy.$modal.msgError('跟进时间不能为空')
        return false
      }
      if (!formParams.value.content) {
        proxy.$modal.msgError('跟进内容不能为空')
        return false
      }
      if (isOutflowName.value == true && !formParams.value.outflowName) {
        proxy.$modal.msgError('流失商机原因不能为空')
        return false
      }
      let param = JSON.parse(JSON.stringify(formParams.value))
      param.sysAttachFiles = fileList.value || []
      delete param.isVisible
      delete param.businessType
      delete param.fileList
      let { url, businessId } = followUrl(props.dialogParam.tableName)
      bidOpeningMsg()
      // const resp = bidOpeningMsg()
      // if (!resp) {
      //   return
      // }
      // btnLoading.value = true
      try {
        if (formParams.value.tableName == 'biz_customer') {
          //客户模块 跟进接口
          const followupRes = await Api.saveFollowUpCustomer(param)
          if (followupRes.code === 200) {
            proxy.$modal.msgSuccess('操作成功')
            btnLoading.value = false
            msgData.value.url = url
            msgData.value.businessId = businessId
            if (formParams.value.principalId) {
              addManage(msgData.value)
            }
            handleClose()
          }
        } else if (formParams.value.tableName == 'ord_business_opportunity') {
          //商机模块 跟进接口
          const followupRes = await Api.saveFollowUpBusiness(param)
          if (followupRes.code === 200) {
            proxy.$modal.msgSuccess('操作成功')
            btnLoading.value = false
            msgData.value.url = url
            msgData.value.businessId = businessId
            if (formParams.value.principalId) {
              addManage(msgData.value)
            }
            handleClose()
          }
        } else {
          //其他业务 跟进接口
          const followupRes = await Api.addSysfucommit(param)
          if (followupRes.code === 200) {
            proxy.$modal.msgSuccess('操作成功')
            btnLoading.value = false
            msgData.value.url = url
            msgData.value.businessId = businessId
            if (formParams.value.principalId) {
              addManage(msgData.value)
            }
            handleClose()
          }
        }
      } catch (error) {
        btnLoading.value = false
      }
    }
  })
}
/*** 文件上传 start */
let fileList = ref([])
/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}
// 上传合同
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
/*****文件上传 end */
/***客户联系人数据  start*/
const contactsOptions = ref([])
/**
 * 客户联系人模糊搜索
 * @param val 当前输入的值
 */
async function queryContacts(val) {
  let params = {
    pageSize: 10,
    entId: formParams.value.businessId,
    contactName: val
  }
  await getDetailTactlistByCactName(params).then(res => {
    contactsOptions.value = res.data
  })
}
// 客户联系人选中事件
const contactsChange = val => {
  let newData = JSON.parse(JSON.stringify(contactsOptions.value))
  let obj = newData.filter(item => {
    return (item.id = val)
  })
  formParams.value.linkName = obj[0].contactName
}
/***客户联系人数据  end*/
/**** 项目负责人 模块 start */

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  dialogParamUse.value = {
    type: 'principalId',
    title: '请选择提醒谁看',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: true,
    checkStrictly: false,
    apiParams: { deptId: 100 }
  }
  dialogParamUse.value.isDialog = true
  dialogParamUse.value.defaultCheckedKeys = formParams.value.principalId || []
}
/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'principalId':
      console.log(val)
      selectOptionObj.value['principalId'] = val.selectData
      formParams.value.principal = val.labelData.toString()
      formParams.value.principalId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      break
  }
}
const closeFn = val => {
  dialogParamUse.value.isDialog = false
}
/**** 项目负责人 模块 end */
const emit = defineEmits(['close'])
// 取消
function handleClose() {
  btnLoading.value = false
  dialogVisible.value = false
  formParams.value = {}
  fileList.value = []
  emit('close', 'followUp')
}

const objTitle = {
  biz_customer: '客户详情',
  ord_project: '项目详情',
  ord_order: '订单详情',
  biz_contact: '联系人详情'
}

function bidOpeningMsg() {
  const objName = {
    biz_customer: formParams.value.customer ? formParams.value.customer : '',
    ord_project: formParams.value.proName ? formParams.value.proName : '',
    ord_order: formParams.value.orderName ? formParams.value.orderName : '',
    biz_contact: formParams.value.linkName ? formParams.value.linkName : '',
    ord_business_opportunity: formParams.value.customer
      ? formParams.value.customer
      : '',
    ord_small_medium: formParams.value.customer
      ? formParams.value.customer
      : '',
    ord_purchase_order: formParams.value.orderName
      ? formParams.value.orderName
      : '',
    ord_inner_order: formParams.value.orderName
      ? formParams.value.orderName
      : ''
  }
  const titleName = {
    ord_small_medium: `${objName[formParams.value.tableName]}商机待跟进`
  }

  if (formParams.value.rebid === '0') {
    return true
  }
  const obj = {}
  let resp = true
  const time = formParams.value.followTime
    ? format(new Date(new Date().getTime()), 'yyyy-MM-dd 00:00:00')
    : ''
  obj.receiver = (
    formParams.value.principalId ? formParams.value.principalId : []
  )
    .toString()
    .replace(/U/gi, '')
  obj.content = `${objName[formParams.value.tableName]}跟进：${
    formParams.value.content
  }`

  // obj.sendTime = time
  obj.sendTime = formParams.value.remindTime
  obj.reminderMethod = '1'
  obj.impSign = '2'
  obj.serviceType = serviceType.value
  obj.urgFlag = '1'
  obj.receiverName = formParams.value.principal
  obj.followDate = formParams.value.followTime
  obj.urlName = '前往详情'
  obj.title = titleName[formParams.value.tableName]
    ? titleName[formParams.value.tableName]
    : `关于${objName[formParams.value.tableName]}的跟进提醒`
  obj.type = '0'
  obj.sender = userStore.user.nickName
  // 项目验收计划
  // const result = pushNotifications(obj, ['receiver'])
  // if (!result) {
  //   proxy.$modal.msgWarning('消息提醒存在未填内容，请先填写完整')
  //   resp = false
  // } else {
  msgData.value = obj
  // }
  // return resp
}
const isOutflowName = ref(false)
// 商机阶段 选中
// 选中流失商机 才出现流失商机原因
const businessStage = val => {
  console.log(val, '111111111111')
  isOutflowName.value = val == 5 ? true : false
}
// 流失商机 选中
const outflowCodeFn = val => {
  const outflowCode = JSON.parse(
    JSON.stringify(toRaw(lost_business_opportunities.value))
  )
  const obj = outflowCode.find(v => v.value == val)
  formParams.value.outflowName = obj ? obj.label : ''
}
</script>
<style lang="scss">
.dialogStyle {
  border-radius: 10px;
  .el-dialog__header {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    @apply mr-0  text-#666 font-semibold bg-#f5f5f5;
  }
  .footer {
    @apply text-right border-t border-t-solid border-gray-100 pt-20px mt-20px;
  }
}
</style>
